<!DOCTYPE html>
<html lang="en">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="My Personal Website For Blog">
  <meta name="author" content="黄宇辉">
  <meta name="keywords" content="learning note,hexo blog">
  <title>Java web:Cookie and Session - 欢迎参观小灰灰的网站哟 ヾ(◍°∇°◍)ﾉﾞ ~</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/vs2015.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->
<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">

<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">

<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>ANONYMOUS</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                Home
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                Archives
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                Tags
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                About
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2019-05-02 09:33">
      May 2, 2019 am
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      65
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h2 id="学习笔记-Java-web之会话及其会话技术"><a href="#学习笔记-Java-web之会话及其会话技术" class="headerlink" title="学习笔记 : Java web之会话及其会话技术"></a>学习笔记 : Java web之会话及其会话技术</h2><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p><em>在Web开发中,服务器跟踪用户信息的技术成为会话技术,它指的是一个客户端(浏览器)与Web服务器之间连续发生的一系列请求和响应的过程.为了保存会话过程中产生的数据,在Servlet技术中,提供了两个用于保存会话数据的对象,分别是<code>Cookie</code>和<code>Session</code>.</em></p>
<h3 id="Cookie-object"><a href="#Cookie-object" class="headerlink" title="Cookie object"></a>Cookie object</h3><p><em><code>Cooke</code>是一种会话技术,它用于将会话过程中的数据保存到用户的浏览器中,从而使浏览器和服务器可以更好地进行数据交互.Cookie在浏览器和服务器之间的传输过程示例图如下 :</em></p>
<p><img src="/2019/05/02/Java-web-Cookie-and-Session/Cookie%E5%9C%A8%E6%B5%8F%E8%A7%88%E5%99%A8%E5%92%8C%E6%9C%8D%E5%8A%A1%E5%99%A8%E4%B9%8B%E9%97%B4%E7%9A%84%E4%BC%A0%E8%BE%93%E8%BF%87%E7%A8%8B.jpg" srcset="/img/loading.gif" alt=" "></p>
<h3 id="Cookie-application"><a href="#Cookie-application" class="headerlink" title="Cookie application"></a>Cookie application</h3><h4 id="显示用户上次访问时间"><a href="#显示用户上次访问时间" class="headerlink" title="显示用户上次访问时间"></a>显示用户上次访问时间</h4><p><em>案例描述 : 当用户请求LastAccessServlet时,服务器会调用<code>HttpServletResponse</code>接口的<code>addCookie(Cookie cookie)</code>方法,该方法会在发送给浏览器的HTTP响应消息中增加一个<code>Set-Cookie</code>头字段,将创建的Cookie对象作为Set-Cookie头字段的值传递给浏览器.示例程序如下 :</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/LastAccessServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LastAccessServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">LastAccessServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		String lastAccessTime = <span class="hljs-keyword">null</span>;<span class="hljs-comment">// 最后一次登录的时间</span>

		<span class="hljs-comment">// 获取所有cookie,并将其存放到数组中</span>
		Cookie[] cookies = request.getCookies();
		<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; cookies != <span class="hljs-keyword">null</span> &amp;&amp; i &lt; cookies.length; i++) &#123;
			<span class="hljs-comment">// 如果cookie的名称为lastAccess,则获取其对应的cookie值</span>
			<span class="hljs-keyword">if</span> (<span class="hljs-string">"lastAccess"</span>.equals(cookies[i].getName())) &#123;
				lastAccessTime = cookies[i].getValue();
				<span class="hljs-keyword">break</span>;
			&#125;
		&#125;

		<span class="hljs-comment">// 判断是否存在名称为lastAccess的cookie</span>
		<span class="hljs-keyword">if</span> (lastAccessTime == <span class="hljs-keyword">null</span>) &#123;
			response.getWriter().println(<span class="hljs-string">"the first to visit this page !"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			response.getWriter().println(<span class="hljs-string">"the time of last visited : "</span> + lastAccessTime);
		&#125;

		<span class="hljs-comment">// 创建cookie,并将当前时间作为名为lastAccess的cookie的值</span>
		String currentTime = <span class="hljs-keyword">new</span> SimpleDateFormat(<span class="hljs-string">"YYYY-MM-dd—&gt;hh:mm:ss"</span>).format(<span class="hljs-keyword">new</span> Date());
		Cookie cookie = <span class="hljs-keyword">new</span> Cookie(<span class="hljs-string">"lastAccess"</span>, currentTime);
		<span class="hljs-comment">// 设置Cookie对象在客户端的存活时长,默认值为 -1</span>
		cookie.setMaxAge(<span class="hljs-number">60</span>);
		<span class="hljs-comment">// 设置该Cookie项的有效目录路径</span>
		cookie.setPath(<span class="hljs-string">"/Cookie-Session_basic"</span>);

		<span class="hljs-comment">// 发送cookie到客户端</span>
		response.addCookie(cookie);
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>


<h3 id="Session-object"><a href="#Session-object" class="headerlink" title="Session object"></a>Session object</h3><p><em><code>Cookie</code>技术可以将用户的信息保存在各自的浏览器中,并且可以在多次请求下实现数据的共享.但是,如果传递的信息比较多,使用Cookie技术显然会增加服务器端程序处理的难度.这时,可以使用<code>Session</code>实现,Session是一种将会话数据保存到服务器端的技术.当浏览器访问Web服务器时,<code>Servlet容器</code>就会创建一个<code>Session对象</code>和<code>ID属性</code>,当客户端后续访问服务器时,只要将标识号传递给服务器,服务器就能判断出该请求是哪个客户端发送的,从而选择与之对应的Session对象为其服务.需要注意的是 : 由于客端户需要接收,记录,回送Session对象的ID,因此,通常情况下,<code>Session是借助Cookie技术来传递ID属性的 !</code></em></p>
<h4 id="HttpSession-API"><a href="#HttpSession-API" class="headerlink" title="HttpSession API"></a>HttpSession API</h4><p><em>Session是与每个请求消息紧密相关的,HttpServletRequest接口中定义了用于获取Session对象的getSession()方法,该方法有两种重载形式.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-comment">// 根据传递的参数来判断是否创建新的HttpSession对象</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> HttpSession <span class="hljs-title">getSession</span><span class="hljs-params">(<span class="hljs-keyword">boolean</span> create)</span></span>;
<span class="hljs-comment">// 在相关的HttpSession对象不存在时总是创建新的HttpSession对象</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> HttpSession <span class="hljs-title">getSession</span><span class="hljs-params">()</span></span>;</code></pre></div>

<h4 id="Session超时管理"><a href="#Session超时管理" class="headerlink" title="Session超时管理"></a>Session超时管理</h4><p><em>为了解决不再使用的<code>HttpSession</code>对象会在Web服务器中因积累过多从而导致Web服务器内存耗尽的问题,Web服务器采用了<code>超时限制</code>的办法来判断客户端是否还在继续访问.在会话过程中,会话的有效时间可以在<code>web.xml</code>文件中设置,其默认值由Servlet容器定义.如果想使站点内的所有Web应用程序都起作用,可以配置<code>&lt;Tomcat directory&gt;\conf\web.xml</code>文件,如下所示 :</em></p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- ==================== Default Session Configuration ================= --&gt;</span>
  <span class="hljs-comment">&lt;!-- You can set the default session timeout (in minutes) for all newly --&gt;</span>
  <span class="hljs-comment">&lt;!-- created sessions by modifying the value below.                     --&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">session-config</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">session-timeout</span>&gt;</span>30<span class="hljs-tag">&lt;/<span class="hljs-name">session-timeout</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">session-config</span>&gt;</span></code></pre></div>


<h3 id="Session-application"><a href="#Session-application" class="headerlink" title="Session application"></a>Session application</h3><h4 id="实现购物车"><a href="#实现购物车" class="headerlink" title="实现购物车"></a>实现购物车</h4><p><em>案例描述 : 购物车的的实现流程如下图所示,当用户使用浏览器访问某个网站的图书列表页面时,如果购买某一本书,那么首先会判断书籍是否存在,如果存在就加入购物车,跳转到购物车中所购买图书的列表页,否则,返回图书列表页面.</em></p>
<p><img src="/2019/05/02/Java-web-Cookie-and-Session/Session%E6%A1%88%E4%BE%8B-%E8%B4%AD%E7%89%A9%E8%BD%A6%E7%9A%84%E5%AE%9E%E7%8E%B0%E6%B5%81%E7%A8%8B%E5%9B%BE.png" srcset="/img/loading.gif" alt=" "></p>
<ol>
<li><p><em>Book.java : 用于封装图书的信息.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.shoppingtrolley;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: Book
 * <span class="hljs-doctag">@Description</span>: 封装图书的信息
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 4:52:20 PM
 * 
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> </span>&#123;

	<span class="hljs-keyword">private</span> String id;
	<span class="hljs-keyword">private</span> String name;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Book</span><span class="hljs-params">(String book_id, String book_name)</span> </span>&#123;
		id = book_id;
		name = book_name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> id;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(String id)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.id = id;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> name;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.name = name;
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>BookDB.java : 用于模拟保存所有图书的数据库.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.shoppingtrolley;

<span class="hljs-keyword">import</span> java.util.Collection;
<span class="hljs-keyword">import</span> java.util.LinkedHashMap;
<span class="hljs-keyword">import</span> java.util.Map;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: BookDB
 * <span class="hljs-doctag">@Description</span>: 模拟保存所有图书的数据库
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 4:56:02 PM
 * 
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BookDB</span> </span>&#123;

	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Map&lt;String, Book&gt; books = <span class="hljs-keyword">new</span> LinkedHashMap&lt;String, Book&gt;();

	<span class="hljs-keyword">static</span> &#123;

		books.put(<span class="hljs-string">"1"</span>, <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"1"</span>, <span class="hljs-string">"《Java web 入门》"</span>));
		books.put(<span class="hljs-string">"2"</span>, <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"2"</span>, <span class="hljs-string">"《Java web 进阶》"</span>));
		books.put(<span class="hljs-string">"3"</span>, <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"3"</span>, <span class="hljs-string">"《Spring》"</span>));
		books.put(<span class="hljs-string">"4"</span>, <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"4"</span>, <span class="hljs-string">"《Spring MVC》"</span>));
		books.put(<span class="hljs-string">"5"</span>, <span class="hljs-keyword">new</span> Book(<span class="hljs-string">"5"</span>, <span class="hljs-string">"《MyBatis》"</span>));
	&#125;

	<span class="hljs-comment">// 获取所有的图书</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Collection&lt;Book&gt; <span class="hljs-title">getall</span><span class="hljs-params">()</span> </span>&#123;

		<span class="hljs-keyword">return</span> books.values();
	&#125;

	<span class="hljs-comment">// 根据指定的id获取图书</span>
	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Book <span class="hljs-title">getBook</span><span class="hljs-params">(String book_id)</span> </span>&#123;
		<span class="hljs-keyword">return</span> books.get(book_id);
	&#125;
&#125;</code></pre></div>
</li>
<li><p><em>ListBookServlet.java : 用于显示所有可购买图书的列表.通过点击”click to buy”链接,便可将指定的图书添加到购物车中.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.shoppingtrolley;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.PrintWriter;
<span class="hljs-keyword">import</span> java.util.Collection;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: ListBookServlet
 * <span class="hljs-doctag">@Description</span>: 显示所有可购买图书的列表
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 5:05:12 PM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/ListBookServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ListBookServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ListBookServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		PrintWriter printWriter = response.getWriter();
		Collection&lt;Book&gt; bookInfo = BookDB.getall();

		printWriter.println(<span class="hljs-string">"&lt;h3 align='center'&gt;All of book be shown as followed&lt;/h3&gt;&lt;hr/&gt;"</span>);
		<span class="hljs-keyword">for</span> (Book book : bookInfo) &#123;
			String url = <span class="hljs-string">"/Cookie-Session_basic/PurchaseServlet?id="</span> + book.getId();
			printWriter.println(book.getName() + <span class="hljs-string">"&lt;a href=' "</span> + url + <span class="hljs-string">" '&gt;click to buy ..&lt;/a&gt;&lt;br&gt;"</span>);
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>PurchaseServlet.java : 功能一: 将用户购买的图书信息保存到Session对象中. 功能二: 在用户购买图书结束后,将页面重定向到用户已经购买的图书列表.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.shoppingtrolley;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.Cookie;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpSession;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: PurchaseServlet
 * <span class="hljs-doctag">@Description</span>: 购买图书
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: May 2, 2019 5:17:54 PM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/PurchaseServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PurchaseServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PurchaseServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// 获得用户购买的商品</span>
		String book_id = request.getParameter(<span class="hljs-string">"id"</span>);

		<span class="hljs-comment">// 如果book_id为空,重定向到ListBookServlet页面</span>
		<span class="hljs-keyword">if</span> (book_id == <span class="hljs-keyword">null</span>) &#123;
			response.sendRedirect(<span class="hljs-string">"/ListBookServlet"</span>);
			<span class="hljs-keyword">return</span>;
		&#125;
		Book book = BookDB.getBook(book_id);

		<span class="hljs-comment">// 创建/获取用户的Session对象</span>
		HttpSession session = request.getSession();

		<span class="hljs-comment">// 从Session对象中获得用户的购物车</span>
		<span class="hljs-meta">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
		List&lt;Book&gt; cart = (List&lt;Book&gt;) session.getAttribute(<span class="hljs-string">"cart"</span>);
		<span class="hljs-keyword">if</span> (cart == <span class="hljs-keyword">null</span>) &#123;
			<span class="hljs-comment">// 首次购买,为用户创建一个购物车( 用List集合模拟购物车 )</span>
			cart = <span class="hljs-keyword">new</span> ArrayList&lt;Book&gt;();
			<span class="hljs-comment">// 将购物车存入到Session对象中</span>
			session.setAttribute(<span class="hljs-string">"cart"</span>, cart);
		&#125;

		<span class="hljs-comment">// 将商品放入购物车</span>
		cart.add(book);

		<span class="hljs-comment">// 创建Cookie存放Session的标识号( 体现了Session是借助Cookie技术来传递ID属性的 )</span>
        <span class="hljs-comment">// JSeesionID: Tomcat容器对SessionID的称呼</span>
		Cookie cookie = <span class="hljs-keyword">new</span> Cookie(<span class="hljs-string">"JSessionID"</span>, session.getId());
		cookie.setMaxAge(<span class="hljs-number">60</span> * <span class="hljs-number">30</span>);
		cookie.setPath(<span class="hljs-string">"/Cookie-Session_basic"</span>);

		<span class="hljs-comment">// 重定向到购物车页面</span>
		response.sendRedirect(<span class="hljs-string">"/Cookie-Session_basic/CartServlet"</span>);

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>CartServlet.java : 展示用户已经购买的图书列表.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.shoppingtrolley;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.PrintWriter;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpSession;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: CartServlet
 * <span class="hljs-doctag">@Description</span>: 展示用户已购买的图书列表
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 5:30:42 PM
 *
 */</span>
<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/CartServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CartServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">CartServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-meta">@SuppressWarnings</span>(<span class="hljs-string">"unchecked"</span>)
	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		PrintWriter printWriter = response.getWriter();

		<span class="hljs-comment">// 引用用户的购物车</span>
		List&lt;Book&gt; cart = <span class="hljs-keyword">null</span>;
		<span class="hljs-comment">// 标记用户是否买过商品</span>
		<span class="hljs-keyword">boolean</span> purFlag = <span class="hljs-keyword">true</span>;

		<span class="hljs-comment">// 获得用户的session</span>
		HttpSession session = request.getSession(<span class="hljs-keyword">false</span>);
		<span class="hljs-keyword">if</span> (session == <span class="hljs-keyword">null</span>) &#123;
			purFlag = <span class="hljs-keyword">false</span>;
		&#125; <span class="hljs-keyword">else</span> &#123;
			<span class="hljs-comment">// 获得用户购物车</span>
			cart = (List&lt;Book&gt;) session.getAttribute(<span class="hljs-string">"cart"</span>);
			<span class="hljs-comment">// 如果用户的购物车为空</span>
			<span class="hljs-keyword">if</span> (cart == <span class="hljs-keyword">null</span>) &#123;
				purFlag = <span class="hljs-keyword">false</span>;
			&#125;
		&#125;

		<span class="hljs-keyword">if</span> (!purFlag) &#123;
			printWriter.println(<span class="hljs-string">"Sorry,you don't buy any books ..."</span>);
			response.sendRedirect(<span class="hljs-string">"/ListServlet"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			<span class="hljs-comment">// 显示用户所购买图书的信息</span>
			printWriter.println(<span class="hljs-string">"&lt;h3 align='center'&gt;the book be shown as followed which you had bought&lt;/h3&gt;&lt;hr/&gt;"</span>);
			<span class="hljs-keyword">for</span> (Book book : cart) &#123;
				printWriter.println(book.getName() + <span class="hljs-string">"&lt;br&gt;"</span>);
			&#125;
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>


</li>
</ol>
<h4 id="实现用户登录"><a href="#实现用户登录" class="headerlink" title="实现用户登录"></a>实现用户登录</h4><p><em>案例描述 : 当用户进入网站首页时,如果还未登录,则可以通过单击”登录”按钮进入登录界面.在用户登录时,如果用户名及密码正确则登录成功,否则登录失败.登录成功后还可以单击”退出”按钮,回到首页,显示未登录时的界面.用户登录流程图如下所示 :</em></p>
<p><img src="/2019/05/02/Java-web-Cookie-and-Session/Session%E6%A1%88%E4%BE%8B-%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95%E6%B5%81%E7%A8%8B%E5%9B%BE.png" srcset="/img/loading.gif" alt=" "></p>
<ol>
<li><p><em>Login.html : 用户登录页面.</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>User login interface<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>Login in<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">hr</span>/&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"LoginServlet"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>User name<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
						<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
						<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"userpassword"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
						<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
				<span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">"submit"</span>/&gt;</span>
			<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
		<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>
</li>
<li><p><em>User.java : 封装用户信息.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.login;

<span class="hljs-comment">/**
 * <span class="hljs-doctag">@ClassName</span>: User
 * <span class="hljs-doctag">@Description</span>: 封装用户的信息
 * <span class="hljs-doctag">@author</span>: HuangYuhui
 * <span class="hljs-doctag">@date</span>: Apr 29, 2019 9:21:28 PM
 * 
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>&#123;

	<span class="hljs-keyword">private</span> String username;
	<span class="hljs-keyword">private</span> String password;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">(String name, String password)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.username = name;
		<span class="hljs-keyword">this</span>.password = password;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getUsername</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> username;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUsername</span><span class="hljs-params">(String username)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.username = username;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getPassword</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">return</span> password;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPassword</span><span class="hljs-params">(String password)</span> </span>&#123;
		<span class="hljs-keyword">this</span>.password = password;
	&#125;

&#125;</code></pre></div>


</li>
</ol>
<ol start="3">
<li><p><em>IndexServlet.java : 用于显示网站的首界面,如果用户没有登录,那么首界面需要提示用户登录,否则,显示用户已经登录的信息.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/IndexServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IndexServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">IndexServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		<span class="hljs-comment">// 创建/获取保存用户信息的Session对象</span>
		HttpSession session = request.getSession();

		User user = (User) session.getAttribute(<span class="hljs-string">"user"</span>);
		<span class="hljs-keyword">if</span> (user == <span class="hljs-keyword">null</span>) &#123;
			response.getWriter().println(<span class="hljs-string">"你还没有登录 ! 请&lt;a href='Login.jsp'&gt;登录&lt;/a&gt;"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			response.getWriter().println(<span class="hljs-string">"你已经登录 ! 欢迎你 : "</span> + user.getUsername() + <span class="hljs-string">" !"</span>);
			String url = <span class="hljs-string">"LogoutServlet2"</span>;
			response.getWriter().println(<span class="hljs-string">"&lt;a href=' "</span> + url + <span class="hljs-string">" '&gt;退出&lt;/a&gt;"</span>);

			<span class="hljs-comment">// 创建Cookie用于存放Session标识号</span>
			Cookie cookie = <span class="hljs-keyword">new</span> Cookie(<span class="hljs-string">"JSessionID"</span>, session.getId());
			cookie.setMaxAge(<span class="hljs-number">60</span> * <span class="hljs-number">30</span>);
			cookie.setPath(<span class="hljs-string">"/Cookie-Session_basic"</span>);

			response.addCookie(cookie);
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>LoginServlet.java : 用于显示用户登录成功后的界面.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/LoginServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">LoginServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		PrintWriter printWriter = response.getWriter();

		String username = request.getParameter(<span class="hljs-string">"username"</span>);
		String password = request.getParameter(<span class="hljs-string">"userpassword"</span>);

		<span class="hljs-keyword">if</span> (<span class="hljs-string">"YUbuntu0109"</span>.equals(username) &amp;&amp; <span class="hljs-string">"demo"</span>.equals(password)) &#123;
			<span class="hljs-comment">// 传递用户登录信息</span>
			User user = <span class="hljs-keyword">new</span> User(username, password);
			request.getSession().setAttribute(<span class="hljs-string">"user"</span>, user);
			response.sendRedirect(<span class="hljs-string">"/Cookie-Session_basic/IndexServlet"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			printWriter.println(<span class="hljs-string">"登录失败 ! 用户名或密码错误 ! &lt;a href='Login.html'&gt;重新登录&lt;/a&gt;"</span>);
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>LogoutServlet.java : 用于完成用户注销功能.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/LogoutServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LogoutServlet</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">LogoutServlet</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		
		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);

		<span class="hljs-comment">// 将Session对象中的User对象移除</span>
		request.getSession().removeAttribute(<span class="hljs-string">"user"</span>);
		response.getWriter().println(<span class="hljs-string">"你的账户已成功注销 ! &lt;a href='Login.html'&gt;返回登录页面&lt;/a&gt;"</span>);

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>


</li>
</ol>
<h4 id="利用Session实现一次性验证码"><a href="#利用Session实现一次性验证码" class="headerlink" title="利用Session实现一次性验证码"></a>利用Session实现一次性验证码</h4><p><em>案例描述 : 在实际开发中,为了保证用户信息的安全,都会在网站登录的界面中添加一次性验证码,从而限制不法分子使用软件暴力猜测密码.一次性验证码的功能同样可以使用<code>Session</code>来实现.该案例代码基于上个案例(实现用户登录)进行改写.</em></p>
<ol>
<li><p><em>Login.jsp : 用户登录页面.</em></p>
<div class="hljs"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">%@</span> <span class="hljs-attr">page</span> <span class="hljs-attr">language</span>=<span class="hljs-string">"java"</span> <span class="hljs-attr">contentType</span>=<span class="hljs-string">"text/html; charset=UTF-8"</span>
    <span class="hljs-attr">pageEncoding</span>=<span class="hljs-string">"UTF-8"</span>%&gt;</span>
<span class="hljs-meta">&lt;!DOCTYPE html&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Login in<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
	<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
	<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>User login interface<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
		<span class="hljs-tag">&lt;<span class="hljs-name">hr</span>/&gt;</span>
			<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">align</span>=<span class="hljs-string">"center"</span>&gt;</span>
				<span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"LoginServlet2"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
					<span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>User name<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"userName"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
							<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Password<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"userPassword"</span>/&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
							<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
							<span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>verification code<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
								<span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>
									<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"verificationCode"</span>/&gt;</span>
									<span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"CheckServlet"</span>/&gt;</span>
								<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
							<span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
					<span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
					<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>  <span class="hljs-attr">value</span>=<span class="hljs-string">"submit"</span>/&gt;</span>
				<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
			<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
		<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre></div>
</li>
<li><p><em>CheckServlet.java : 用于生成验证码图片.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.verifcode;

<span class="hljs-keyword">import</span> java.awt.Color;
<span class="hljs-keyword">import</span> java.awt.Font;
<span class="hljs-keyword">import</span> java.awt.Graphics;
<span class="hljs-keyword">import</span> java.awt.image.BufferedImage;
<span class="hljs-keyword">import</span> java.io.ByteArrayOutputStream;
<span class="hljs-keyword">import</span> java.io.IOException;

<span class="hljs-keyword">import</span> javax.imageio.ImageIO;
<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.ServletOutputStream;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpSession;

<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/CheckServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CheckServlet2</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> WIDTH = <span class="hljs-number">100</span>;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> HEIGHT = <span class="hljs-number">30</span>;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		<span class="hljs-comment">// set specifying the MIME type of the content</span>
		response.setContentType(<span class="hljs-string">"image/jpeg"</span>);

		<span class="hljs-comment">// 设置浏览器勿缓冲此图片</span>
		response.setHeader(<span class="hljs-string">"Pragma"</span>, <span class="hljs-string">"No-cache"</span>);
		response.setHeader(<span class="hljs-string">"Cache-Control"</span>, <span class="hljs-string">"no-cache"</span>);
		response.setDateHeader(<span class="hljs-string">"Expiress"</span>, <span class="hljs-number">0</span>);

		<span class="hljs-comment">// 获取/创建Session对象</span>
		HttpSession session = request.getSession();

		<span class="hljs-comment">// 创建内存图像并获得其图像上下文</span>
		BufferedImage bufferedImage = <span class="hljs-keyword">new</span> BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_BGR);
		<span class="hljs-comment">// 绘制图像</span>
		Graphics graphics = bufferedImage.getGraphics();
		<span class="hljs-comment">// 产生随机的认证码</span>
		<span class="hljs-keyword">char</span>[] rands = generateCheckCode();
		<span class="hljs-comment">// 产生图像</span>
		drawBackground(graphics);
		drawRands(graphics, rands);
		<span class="hljs-comment">// 结束图形的绘制过程</span>
		graphics.dispose();

		<span class="hljs-comment">// 将图像输出到客户端</span>
		ByteArrayOutputStream byteArrayOutputStream = <span class="hljs-keyword">new</span> ByteArrayOutputStream();
		<span class="hljs-comment">// writes an image using an arbitrary ImageWriterthat supports the given format</span>
		<span class="hljs-comment">// to an OutputStream.</span>
		ImageIO.write(bufferedImage, <span class="hljs-string">"JPEG"</span>, byteArrayOutputStream);

		<span class="hljs-comment">// Sets the length of the content body in the response In HTTP servlets,</span>
		<span class="hljs-comment">// this method sets the HTTP Content-Length header.</span>
		<span class="hljs-keyword">byte</span>[] buff = byteArrayOutputStream.toByteArray();
		response.setContentLength(buff.length);

		<span class="hljs-comment">// 将图片写入到Servlet输出流</span>
		ServletOutputStream servletOutputStream = response.getOutputStream();
		byteArrayOutputStream.writeTo(servletOutputStream);
		byteArrayOutputStream.close();
		servletOutputStream.close();

		<span class="hljs-comment">// 将当前验证码存放到Session中</span>
		session.setAttribute(<span class="hljs-string">"check_code"</span>, <span class="hljs-keyword">new</span> String(rands));
		<span class="hljs-comment">// 直接使用下述代码将有问题! 因为Session对象必须在提交响应前获得</span>
		<span class="hljs-comment">// request.getSession().setAttribute("check_code", new String(rands));</span>
	&#125;

	<span class="hljs-comment">// 生成验证码</span>
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">char</span>[] generateCheckCode() &#123;
		String chars = <span class="hljs-string">"0123456789abcdefghijklmnopqrstuvwxyz"</span>
				+ <span class="hljs-string">"ABCDEFGHIJKLMNOPQRSTUVWXYZ"</span>;
		<span class="hljs-keyword">char</span>[] rands = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[<span class="hljs-number">4</span>];
		<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">4</span>; i++) &#123;
			<span class="hljs-keyword">int</span> rand = (<span class="hljs-keyword">int</span>) (Math.random() * (<span class="hljs-number">10</span> + <span class="hljs-number">26</span> * <span class="hljs-number">2</span>));
			rands[i] = chars.charAt(rand);
		&#125;
		<span class="hljs-keyword">return</span> rands;
	&#125;

	<span class="hljs-comment">// 绘制验证码</span>
	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawRands</span><span class="hljs-params">(Graphics g, <span class="hljs-keyword">char</span>[] rands)</span> </span>&#123;
		g.setColor(Color.RED);
		g.setFont(<span class="hljs-keyword">new</span> Font(<span class="hljs-string">"Console"</span>, Font.BOLD, <span class="hljs-number">25</span>));

		<span class="hljs-comment">// 在不同的坐标上输出每个字符</span>
		g.drawString(<span class="hljs-string">""</span> + rands[<span class="hljs-number">0</span>], <span class="hljs-number">10</span>, <span class="hljs-number">22</span>);
		g.drawString(<span class="hljs-string">""</span> + rands[<span class="hljs-number">1</span>], <span class="hljs-number">30</span>, <span class="hljs-number">22</span>);
		g.drawString(<span class="hljs-string">""</span> + rands[<span class="hljs-number">2</span>], <span class="hljs-number">50</span>, <span class="hljs-number">22</span>);
		g.drawString(<span class="hljs-string">""</span> + rands[<span class="hljs-number">3</span>], <span class="hljs-number">70</span>, <span class="hljs-number">22</span>);
	&#125;

	<span class="hljs-comment">// 绘制图片背景</span>
	<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawBackground</span><span class="hljs-params">(Graphics g)</span> </span>&#123;

		<span class="hljs-comment">// 画背景</span>
		g.setColor(Color.LIGHT_GRAY);
		g.fillRect(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, WIDTH, HEIGHT);

		<span class="hljs-comment">// 随机产生200个干扰点</span>
		<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">200</span>; i++) &#123;
			<span class="hljs-keyword">int</span> x = (<span class="hljs-keyword">int</span>) (Math.random() * WIDTH);
			<span class="hljs-keyword">int</span> y = (<span class="hljs-keyword">int</span>) (Math.random() * HEIGHT);
			<span class="hljs-keyword">int</span> red = (<span class="hljs-keyword">int</span>) (Math.random() * <span class="hljs-number">255</span>);
			<span class="hljs-keyword">int</span> green = (<span class="hljs-keyword">int</span>) (Math.random() * <span class="hljs-number">255</span>);
			<span class="hljs-keyword">int</span> blue = (<span class="hljs-keyword">int</span>) (Math.random() * <span class="hljs-number">255</span>);

			g.setColor(<span class="hljs-keyword">new</span> Color(red, green, blue));
			g.drawOval(x, y, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>);<span class="hljs-comment">// draws the outline of an oval</span>

		&#125;
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>LoginServlet.java : 对LoginServlet进行修改,增加对验证码的判断.</em></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">package</span> pers.huangyuhui.session.example.verifcode;

<span class="hljs-keyword">import</span> java.io.IOException;
<span class="hljs-keyword">import</span> java.io.PrintWriter;

<span class="hljs-keyword">import</span> javax.servlet.ServletException;
<span class="hljs-keyword">import</span> javax.servlet.annotation.WebServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServlet;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletRequest;
<span class="hljs-keyword">import</span> javax.servlet.http.HttpServletResponse;

<span class="hljs-meta">@WebServlet</span>(<span class="hljs-string">"/LoginServlet"</span>)
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoginServlet2</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HttpServlet</span> </span>&#123;
	<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> serialVersionUID = <span class="hljs-number">1L</span>;

	<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">LoginServlet2</span><span class="hljs-params">()</span> </span>&#123;
		<span class="hljs-keyword">super</span>();
	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doGet</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;

		response.setContentType(<span class="hljs-string">"text/html;charset=utf-8"</span>);
		PrintWriter printWriter = response.getWriter();

		String name = request.getParameter(<span class="hljs-string">"userName"</span>);
		String password = request.getParameter(<span class="hljs-string">"userPassword"</span>);
		String checkCode = request.getParameter(<span class="hljs-string">"verificationCode"</span>);

		<span class="hljs-comment">/*
		 * 获取Session中的验证码信息
		 */</span>
		String saveCheckCode = (String) request.getSession().getAttribute(<span class="hljs-string">"check_code"</span>);
		<span class="hljs-keyword">if</span> (<span class="hljs-string">"YUbuntu0109"</span>.equals(name) &amp;&amp; <span class="hljs-string">"demo"</span>.equals(password) &amp;&amp; checkCode.equals(saveCheckCode)) &#123;
			User user = <span class="hljs-keyword">new</span> User(name, password);
			request.getSession().setAttribute(<span class="hljs-string">"user"</span>, user);
			response.sendRedirect(<span class="hljs-string">"/Cookie-Session_basic/IndexServlet"</span>);

		&#125; <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (checkCode.equals(saveCheckCode)) &#123;
			printWriter.println(<span class="hljs-string">"登录失败! 用户名或密码 !"</span>);
		&#125; <span class="hljs-keyword">else</span> &#123;
			printWriter.println(<span class="hljs-string">"验证码错误 !"</span>);
		&#125;

	&#125;

	<span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doPost</span><span class="hljs-params">(HttpServletRequest request, HttpServletResponse response)</span>
			<span class="hljs-keyword">throws</span> ServletException, IOException </span>&#123;
		doGet(request, response);
	&#125;

&#125;</code></pre></div>
</li>
<li><p><em>程序运行结果 : 用户登录页面.</em><br><img src="/2019/05/02/Java-web-Cookie-and-Session/Session%E6%A1%88%E4%BE%8B-%E5%AE%9E%E7%8E%B0%E4%B8%80%E6%AC%A1%E6%80%A7%E9%AA%8C%E8%AF%81%E7%A0%81-%E7%94%A8%E6%88%B7%E7%99%BB%E5%BD%95%E9%A1%B5%E9%9D%A2.PNG" srcset="/img/loading.gif" alt=" "></p>
</li>
</ol>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/Java-web/">Java web</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2019/05/02/VOA-Critics-Praise-New-and-Last-Avengers-Series-Film/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">VOA:Critics Praise New and Last Avengers Series Film</span>
                        <span class="visible-mobile">Previous</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2019/05/02/Java-web-Servlet-listener/">
                        <span class="hidden-mobile">Java web:Servlet listener</span>
                        <span class="visible-mobile">Next</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;TOC</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">Search</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">keyword</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


    

    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "Java web:Cookie and Session&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  














</body>
</html>
